<?php
/**
 * 汇友科技
 * @copyright (c) 2017 http://www.huiyou365.net All rights reserved.
 * @author: Creatint <creatint@163.com>
 */
namespace Admin\Controller;

use Admin\Model\AuthGroupModel;
use Admin\Model\AuthRuleModel;

class AuthController extends AdminController{
    public function index(){
        $list = $this['AuthGroup']->get();
        int_to_string($list,['status'=>[1=>'启用',0=>'禁用'],'module'=>['admin'=>'后台模块','home'=>'前台模块'], 'type'=>[0=>'普通用户',1=>'管理员']]);
        $this->assign('list',$list);
        $this->assign('title','权限管理');
        $this->display();
    }

    public function editGroup($id = null){
        if ( IS_POST ) {
            // 编辑
            $info = $_POST;
            $info['rules'] = trim($info['rules'],',');
            if ( $id = $this['AuthGroup']->update($info) ) {
                $info['id'] = $info['id']?$info['id']:$id;
                $_GET['id'] = $id;
                // 设置前台操作结果提示
                $this->alert['msg'] = '操作成功';
                $this->alert['status'] = 1;
                redirect(U('Auth/index'));
            } else {
                // 设置前台操作结果提示
                $this->alert['msg'] = '操作失败 '.$this['AuthGroup']->getError();
                $this->alert['status'] = 0;
            }
            // 前台操作提示
            $this->alert();
        }

        if ( $id >0 ) {
            $info = $this['AuthGroup']->info(['id'=>$id]);
            $title = '编辑用户组';
        } else {
            // 新增
            $info = ['module'=>'admin','status'=>1];
            $title = '新增用户组';
        }

        $this->assign('info',$info);
        $this->assign('title',$title);

        $this->display();
    }

    public function group(){
        $uid            =   I('uid');
        $auth_groups    =   D('AuthGroup')->getGroups();
        $user_groups    =   AuthGroupModel::getUserGroup($uid);
        $ids = array();
        foreach ($user_groups as $value){
            $ids[]      =   $value['group_id'];
        }
        $nickname       =   D('Admin')->getNickName($uid);
        $this->assign('title',   '用户组授权');
        $this->assign('nickname',   $nickname);
        $this->assign('auth_groups',$auth_groups);
        $this->assign('user_groups',implode(',',$ids));
        $this->display();
    }

    public function user($group_id){
        $title = '成员授权';
        if(empty($group_id)){
            $this->error('参数错误');
        }

        // 获得所有用户组,id为索引
        $auth_group = M('AuthGroup')->where( array('status'=>array('egt','0'),'module'=>'admin','type'=>AuthGroupModel::TYPE_ADMIN) )
            ->getfield('id,id,title,rules');
        $prefix   = C('DB_PREFIX');
        $l_table  = $prefix.(AuthGroupModel::MEMBER);
        $r_table  = $prefix.(AuthGroupModel::AUTH_GROUP_ACCESS);
        $model    = M()->table( $l_table.' m' )->join ( $r_table.' a ON m.uid=a.uid' );
        $_REQUEST = array();
        $list = $this->lists($model,array('a.group_id'=>$group_id,'m.status'=>array('egt',0)),'m.uid asc','m.uid,m.username,m.nickname,m.last_login_time,m.last_login_ip,m.status');
        int_to_string($list);
        $this->assign( 'list',     $list );
        $this->assign('auth_group', $auth_group);
        $this->assign('this_group', $auth_group[(int)$_GET['group_id']]);

        $this->display();
    }

    public function access($group_id = null){
        if ( IS_POST ) {
            if(isset($_POST['rules'])){
                sort($_POST['rules']);
                $_POST['rules']  = implode( ',' , array_unique($_POST['rules']));
            }
            $_POST['module'] =  'admin';
            $_POST['type']   =  AuthGroupModel::TYPE_ADMIN;
            $AuthGroup       =  D('AuthGroup');
            $data = $AuthGroup->create();
            if ( $data ) {
                if ( empty($data['id']) ) {
                    $r = $AuthGroup->add();
                }else{
                    $r = $AuthGroup->where(['id'=>$data['id']])->save();
                }
                if($r===false){
                    $this->error('操作失败'.$AuthGroup->getError());
                } else{
                    $this->success('操作成功!',U('index'));
                }
            }else{
                $this->error('操作失败'.$AuthGroup->getError());
            }
        } else {

            $node_list   = $this->returnNodes();

            $auth_group = $this['AuthGroup']->where(['status'=>['egt',0],'module'=>'admin','type'=>AuthGroupModel::TYPE_ADMIN])->field('id,id,title,rules')->getField('id,id,title,rules');

            $map = ['module'=>'admin','type'=>AuthRuleModel::RULE_MAIN,'status'=>1];
            $main_rules = $this['AuthRule']->where($map)->getField( 'name,id');
            $map = ['module'=>'admin','type'=>AuthRuleModel::RULE_URL,'status'=>1];
            $child_rules = $this['AuthRule']->where($map)->getField( 'name,id');



            $this->assign('main_rules', $main_rules);
            $this->assign('auth_rules', $child_rules);
            $this->assign('node_list',  $node_list);
            $this->assign('auth_group', $auth_group);
            $this->assign('this_group', $auth_group[(int)$_GET['group_id']]);

            $this->assign('title', $auth_group[(int)$_GET['group_id']]['title']. ' ' .'访问授权');

            $this->display();
        }

    }


    public function district( $group_id = null, $district_id = null ){
        if ( IS_POST ) {
            if ( empty($group_id) ) {
                $this->error('无用户组ID');
            }

            if ( !D('AuthGroup')->find($district_id) ) {
                $this->error('用户组不存在');
            }

            if ( $district_id && !D('AuthGroup')->checkDistrictId($district_id) ) {
                $this->error(D('AuthGroup')->error);
            }
            if ( D('AuthGroup')->addToDistrict($group_id, $district_id) ) {
                $this->success('操作成功');
            } else {
                $this->error('操作失败');
            }


        } else {
            $auth_group = $this['AuthGroup']->where(['status'=>['egt',0],'module'=>'admin','type'=>AuthGroupModel::TYPE_ADMIN])->field('id,id,title,rules')->getField('id,id,title,rules');
            $district_list = D('District')->get();
            $authed_group = AuthGroupModel::getDistrictOfGroup($group_id);

            $this->assign('list',$district_list);
            $this->assign('authed_group',   implode(',',(array)$authed_group));

            $this->display();
        }
    }


    /**
     * 将用户添加到用户组,入参uid,group_id
     */
    public function addToGroup($notApi = 0){
        $uid = I('post.uid',0);
        $gid = I('post.group_id',0);
        $res = ['msg'=>'','status'=>0];
        if( empty($uid) ){
            $res['msg'] = '参数有误';
            goto res;
        }
        $AuthGroup = D('AuthGroup');
        if(is_numeric($uid)){
            if ( is_administrator($uid) ) {
                $res['msg'] = '该用户为超级管理员';
                goto res;
            }
            if( !M(AuthGroupModel::MEMBER)->where(array('uid'=>$uid))->find() ){
                $res['msg'] = '用户不存在';
                goto res;
            }
        }

        if( $gid && !$AuthGroup->checkGroupId($gid)){
            $res['msg'] = $AuthGroup->error;
            goto res;
        }
        if ( $AuthGroup->addToGroup($uid,$gid) ){
            $res['msg'] = '操作成功';
            $res['status'] = 1;
            $res['data'] = $_POST;
        }else{
            $res['msg'] = $AuthGroup->getError();
        }
        res:
        if (!$notApi) {
            $this->ajaxReturn($res);
        } else {
            if (!$res['status']) {
                $this->error($res['msg']);
            } else {
                redirect(U('User/index'));
            }
        }
    }

    /**
     * 将用户从用户组中移除  入参:uid,group_id
     */
    public function removeFromGroup(){
        $uid = I('uid');
        $gid = I('group_id');
        if( $uid==UID ){
            $this->error('不允许解除自身授权');
        }
        if( empty($uid) || empty($gid) ){
            $this->error('参数有误');
        }
        $AuthGroup = D('AuthGroup');
        if( !$AuthGroup->find($gid)){
            $this->error('用户组不存在');
        }
        if ( $AuthGroup->removeFromGroup($uid,$gid) ){
            $this->success('操作成功');
        }else{
            $this->error('操作失败');
        }
    }


    /**
     * 通用分页列表数据集获取方法
     *
     *  可以通过url参数传递where条件,例如:  index.html?name=asdfasdfasdfddds
     *  可以通过url空值排序字段和方式,例如: index.html?_field=id&_order=asc
     *  可以通过url参数r指定每页数据条数,例如: index.html?r=5
     *
     * @param sting|Model  $model   模型名或模型实例
     * @param array        $where   where查询条件(优先级: $where>$_REQUEST>模型设定)
     * @param array|string $order   排序条件,传入null时使用sql默认排序或模型属性(优先级最高);
     *                              请求参数中如果指定了_order和_field则据此排序(优先级第二);
     *                              否则使用$order参数(如果$order参数,且模型也没有设定过order,则取主键降序);
     *
     * @param boolean      $field   单表模型用不到该参数,要用在多表join时为field()方法指定参数
     * @author 朱亚杰 <xcoolcc@gmail.com>
     *
     * @return array|false
     * 返回数据集
     */
    protected function lists ($model,$where=array(),$order='',$field=true){
        $options    =   array();
        $REQUEST    =   (array)I('request.');
        if(is_string($model)){
            $model  =   M($model);
        }

        $OPT        =   new \ReflectionProperty($model,'options');
        $OPT->setAccessible(true);

        $pk         =   $model->getPk();
        if($order===null){
            //order置空
        }else if ( isset($REQUEST['_order']) && isset($REQUEST['_field']) && in_array(strtolower($REQUEST['_order']),array('desc','asc')) ) {
            $options['order'] = '`'.$REQUEST['_field'].'` '.$REQUEST['_order'];
        }elseif( $order==='' && empty($options['order']) && !empty($pk) ){
            $options['order'] = $pk.' desc';
        }elseif($order){
            $options['order'] = $order;
        }
        unset($REQUEST['_order'],$REQUEST['_field']);

        if(empty($where)){
            $where  =   array('status'=>array('egt',0));
        }
        if( !empty($where)){
            $options['where']   =   $where;
        }
        $options      =   array_merge( (array)$OPT->getValue($model), $options );
        $total        =   $model->where($options['where'])->count();

        if( isset($REQUEST['r']) ){
            $listRows = (int)$REQUEST['r'];
        }else{
            $listRows = C('LIST_ROWS') > 0 ? C('LIST_ROWS') : 10;
        }
        $page = new \Think\Page($total, $listRows, $REQUEST);
        if($total>$listRows){
            $page->setConfig('theme','%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%');
        }
        $p =$page->show();
        $this->assign('_page', $p? $p: '');
        $this->assign('_total',$total);
        $options['limit'] = $page->firstRow.','.$page->listRows;

        $model->setProperty('options',$options);

        return $model->field($field)->select();
    }

    public function deleteGroup($id = null){
        if (!$id) {
            $this->error('无ID');
        }
        if (D('AuthGroup')->remove($id) && D('AuthGroupAccess')->remove(['group_id'=>$id])) {
            redirect(U('Auth/index'));
        } else {
            $this->error('删除失败 '. D('Item')->getError());
        }
    }
}
